"""
光标和目标的绘制与位置更新
"""
import math


class TargetCursorManager:

    def __init__(self, canvas, screen_w, screen_h):
        self.canvas = canvas
        self.screen_w = screen_w
        self.screen_h = screen_h

        # 初始化光标
        self.cursor_pos = [screen_w / 2, screen_h / 2]
        self.cursor = self._create_cursor()

        # 初始化目标
        self.target_pos = [screen_w / 2, screen_h / 2 + 300]
        self.target = self._create_target()

        # 目标位置集合
        self.target_locations = self._generate_target_locations()
        self.current_target_idx = 0

    def _create_cursor(self):
        """创建光标图形"""
        x, y = self.cursor_pos
        return self.canvas.create_oval(
            x - 35, y - 35, x + 35, y + 35,
            fill='red', outline='red'
        )

    def _create_target(self):
        """创建目标图形"""
        x, y = self.target_pos
        return self.canvas.create_oval(
            x - 100, y - 100, x + 100, y + 100,
            fill='', outline='yellow', width=20
        )

    def _generate_target_locations(self):
        """生成所有可能的目标位置"""
        center_x, center_y = self.screen_w / 2, self.screen_h / 2
        radius = 400
        points = []
        for i in range(8):
            angle = math.radians(i * 360 / 8)
            x = center_x + radius * math.cos(angle)
            y = center_y + radius * math.sin(angle)
            points.append((x, y))
        return [points[6], points[2], points[0], points[3], points[4], points[5], points[1], points[7]]

    def update_cursor_position(self, new_x, new_y):
        """更新光标位置（带边界限制）"""
        # 限制光标在安全区域内
        new_x = max(self.screen_w / 2 - 500, min(new_x, self.screen_w / 2 + 500))
        new_y = max(self.screen_h / 2 - 500, min(new_y, self.screen_h / 2 + 500))

        # 移动光标
        dx = new_x - self.cursor_pos[0]
        dy = new_y - self.cursor_pos[1]
        self.canvas.move(self.cursor, dx, dy)
        self.cursor_pos = [new_x, new_y]

    def update_target_position(self, idx):
        """更新目标位置"""
        self.canvas.delete(self.target)  # 删除旧目标
        self.current_target_idx = idx
        self.target_pos = self.target_locations[idx]
        self.target = self._create_target()  # 创建新目标

    def reset_cursor(self):
        """重置光标到初始位置"""
        self.canvas.delete(self.cursor)
        self.cursor_pos = [self.screen_w / 2, self.screen_h / 2]
        self.cursor = self._create_cursor()

    def clear_message(self, text_id):
        """清除成功/失败提示文字"""
        if text_id:
            self.canvas.delete(text_id)
        return None

    def show_message(self, message, color):
        """显示成功/失败提示文字"""
        return self.canvas.create_text(
            100, 100, text=message, font=("Arial", 16), fill=color
        )
